package com.itheima.shop.service;

import com.google.gson.Gson;
import com.itheima.shop.dao.ProductDao;
import com.itheima.shop.entity.Category;
import com.itheima.shop.entity.PageBean;
import com.itheima.shop.entity.Product;
import com.itheima.shop.util.JedisUtil;
import org.apache.commons.beanutils.BeanUtils;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 商品模块-业务层
 */
public class ProductService {
    private ProductDao dao = new ProductDao();
    /**
     * 查询所有商品,输出pageBeanJSON,分页查询
     */
    public PageBean<Product> findAllProductAjax(int currPageNO, int perPageNO) throws Exception {
        PageBean<Product> pageBean = new PageBean<>();

        pageBean.setCurrPageNO(currPageNO);
        pageBean.setPerPageNO(perPageNO);

        int allRecordNO = dao.getAllRecordNO(-1);
        pageBean.setAllRecordNO(allRecordNO);

        int allPageNO = allRecordNO % perPageNO == 0 ? allRecordNO / perPageNO : allRecordNO / perPageNO + 1;
        pageBean.setAllPageNO(allPageNO);

        int start = (currPageNO - 1) * perPageNO;
        int size = perPageNO;
        List<Map<String, Object>> list = dao.findAllProductAjax( start, size);
        List<Product> productList = getProducts(list);
        pageBean.setList(productList);

        return pageBean;
    }

    /**
     * 辅助类
     * 从List<Map<String, Object>>拼接生成List<Product>
     */
    private List<Product> getProducts(List<Map<String, Object>> list) throws IllegalAccessException, InvocationTargetException {
        List<Product> productList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Product product = new Product();
            Category category = new Category();
            BeanUtils.populate(product, map);
            BeanUtils.populate(category, map);
            product.setCategory(category);
            productList.add(product);
        }
        return productList;
    }

    /**
     * 更新商品
     */
    public boolean updateProduct(Product product) throws SQLException {
        return dao.updateProduct(product)>0;
    }
    /**
     * 新增商品
     */
    public boolean addProduct(Product product) throws SQLException {
        return dao.addProduct(product)>0;
    }
    /**
     * 删除商品
     */
    public boolean deleteProduct(int pid) throws SQLException {
        return  dao.deleteProduct(pid)>0;
    }
}
